# -*- coding: utf-8 -*-
# @Author  : pony.guan
# @Time    : 2021/12/27 14:59
# Description:  进度条 & 消息框  & 子线程  & 信号

"""
进度条理解： QProgressBar进度条把每个进度称之为一个step（步骤）
            progressBar.setRange(0,5):  表示一共5个step
            progressBar.setValue(3):通过 setValue 方法，指定当前完成到了哪一步
            可以使用reset()将进度条倒退到开头

技巧： ①耗时任务都要放到子线程中，避免qt界面僵死
      ②不要在子线程中更新主界面，而是子线程发送信号给主线程，由主线程去更新界面


"""
import sys
import time
from threading import Thread

from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox
from PyQt5.QtCore import QObject, pyqtSignal, QSharedMemory
from untitled import Ui_MainWindow


# 信号库
class SignalStore(QObject):
    # 定义一种信号
    progress_update = pyqtSignal(int)
    # 还可以定义其他作用的信号
    finish_task = pyqtSignal()


# 实例化
so = SignalStore()


class MyMainForm(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MyMainForm, self).__init__(parent)
        self.setupUi(self)
        self.pushButton.clicked.connect(self.handle_calc)

        # 信号和槽函数进行绑定
        so.progress_update.connect(self.set_progress)
        so.finish_task.connect(self.finish_task_func)

        # 统计进行中标记，不能同时做两个统计
        self.ongoing = False

    def handle_calc(self) -> None:

        def worker_thread_func(hot_cold_ratio: str, tasks_quantity: int, interval_time: int) -> None:
            """
            @desc 热区活跃程度最高的前tasks_quantity个箱子 与 冷区活跃程度最低的前tasks_quantity个箱子 库位互换
            :param hot_cold_ratio: 热冷库占比
            :param tasks_quantity: 理库任务数量
            :param interval_time: 时间区间(最近多少天)
            :return:
            """
            self.ongoing = True
            for i in range(1, 101):
                time.sleep(0.1)
                so.progress_update.emit(i)
            self.ongoing = False

            so.finish_task.emit()

        if self.ongoing:
            QMessageBox.warning(self, 'Warning', 'Task in progress, please wait for completion')
            return

        # 进一步确认是否执行理库
        reply = QMessageBox.question(self, 'Question', 'About to start, continue or not?',
                                     QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel,
                                     QMessageBox.Cancel)
        if reply != QMessageBox.Yes:
            return

        # 热冷库比例
        hot_cold_ratio = self.comboBox_2.currentText()
        # 理库数量(库位交换数量)
        tasks_quantity = self.spinBox_3.value()
        # 时间区间(最近多少天)
        interval_time = self.spinBox_4.value()
        print(hot_cold_ratio)
        print(type(hot_cold_ratio))
        print(tasks_quantity)
        print(type(tasks_quantity))
        print(interval_time)
        print(type(interval_time))

        worker = Thread(target=worker_thread_func, args=(hot_cold_ratio, tasks_quantity, interval_time))
        worker.start()

    def set_progress(self, value: int) -> None:
        self.progressBar.setValue(value)

    def finish_task_func(self) -> None:
        QMessageBox.information(self, 'Information', 'Finished！')


if __name__ == "__main__":
    app = QApplication(sys.argv)  # 永远是第一行

    # QSharedMemory 防止程序多开
    share = QSharedMemory()
    share.setKey("main_window")
    if share.attach():
        msg_box = QMessageBox()
        # msg_box.setWindowTitle("提示")
        msg_box.setWindowTitle("tips")
        # msg_box.setText("软件已在运行!")
        msg_box.setText("The program is already running!")
        msg_box.setIcon(QMessageBox.Information)
        # msg_box.addButton("确定", QMessageBox.YesRole)
        msg_box.addButton("yes", QMessageBox.YesRole)
        msg_box.exec()
        sys.exit(-1)
    if share.create(1):
        myWin = MyMainForm()
        myWin.show()
        sys.exit(app.exec_())
